import {createSlice} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {deleteWeibo, getWeibo, postWeibo, putWeibo} from "../../api/weibo";

const weiboSlice = createSlice({
    name:'weibo',
    initialState:{
        contentList:[],
        pageNo:1,
        pageSum:1,
        pageSize:5
    },
    reducers:{
        upContentList(state,{payload}){
            state.contentList = payload;
        },
        upWeiboState(state,{payload}){
            state.contentList = payload.contentList
            state.pageNo = payload.pageNo
            state.pageSum = payload.pageSum
            state.pageSize = payload.pageSize
        }

    }
})

export const {upWeiboState} = weiboSlice.actions
//返回仓库数据
export const useGetSelector = ()=>{
    return useSelector(state=>state.weibo)
}
//获取微博
export const getWeiboAsync = (pageNo,pageSize)=>{
    return async (dispatch,getState)=>{
        if(!pageNo)pageNo = getState().weibo.pageNo
        if(!pageSize)pageSize = getState().weibo.pageSize
        const res = await getWeibo(pageNo,pageSize);
        dispatch(upWeiboState({...res,pageSize}))
    }
}
//添加微博
export const postWeiboAsync = (contentRef)=>{
    return async(dispatch)=>{
        const content = contentRef.current.value.trim()
        if(content.length === 0){
            alert("请输入微博内容");
            return;
        }
        await postWeibo(content);// 添加微博
        contentRef.current.value = null;
        dispatch(getWeiboAsync());
    }
}
//删除微博
export const deleteWeiboAsync = (id)=>{
    return async (dispatch)=>{
        await deleteWeibo(id)
        dispatch(getWeiboAsync())
    }
}

//修改微博
export const putWeiboAsync = (id,type)=>{
    return async (dispatch)=>{
        await putWeibo(id,type)
        dispatch(getWeiboAsync())
    }
}

export default weiboSlice.reducer